import axios from 'axios'
import { AxiosResponse, AxiosError } from 'axios'
import { lStorage } from '@utils/tools'
import { JWT_TOKEN } from '@constants/index'
import helper from './httpHelper'
import refreshToken  from './refreshToken'

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

const $http = axios.create({
  baseURL: '',
  responseType: 'json',
  transformResponse: [function (data) {
    return data
  }],
  timeout: 30000
})


$http.interceptors.request.use(config => {
  config.cancelToken = source.token
  if(isTokenTimeOut()){
    source.cancel('请求已取消')
  }
  config.headers.common['Authorization'] = 'Bearer ' + lStorage.get(JWT_TOKEN)
  return config
}, error => {
  return Promise.reject(error)
})



$http.interceptors.response.use(response => {
  helper.successHelper(response)
  return refreshToken.checkStatus(response);
}, error => {
  if(error.response && /^[456]\d{2}$/.test(error.response.status)) {
    helper.errorHelper(error.response)
    return Promise.reject(error.response.data)
  } else {
    $msg.error(error.toString()) // other err: code error
    return Promise.reject(error)
  }
  
})



export default $http
